// pages/register2/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    countdown: 60,
    verifyCode: '',
    verifyCode2: '',
    showErrorMag: false,
    verifyCodeLength: 4,
    phone: '',
    showDxyzmBox: false,
    isPhoneValid: false, // 手机号是否有效
    isModalShow: false, // 控制模态框显示状态
    checked: false, // 初始未选中
    isModalShow2: false
  },
  // 打开模态框
  openModal() {
    this.setData({ isModalShow: true });
  },
  // 关闭模态框
  closeModal() {
    this.setData({ isModalShow: false });
  },
  closeModal2() {
    this.setData({ isModalShow2: false });
  },
  getPhoneNumber () {
     this.handelsuccess()
  },
  onPhoneInput(e) {
    const phone = e.detail.value;
    const regex = /^1[3-9]\d{9}$/; // 手机号正则验证
    this.setData({
      phoneNumber: phone,
      isPhoneValid: regex.test(phone) // 验证结果更新状态
    });
  },
  // 模态框回调事件
  onModalConfirm() {
    this.closeModal();
    this.setData({
      checked: true
    });
    this.setData({showDxyzmBox: true})
  },
  onModalCancel() {
    console.log('用户点击取消');
    this.closeModal();
  },
  handleEmsCode () {
     if (!this.data.checked) {
         this.setData({isModalShow: true})
     } else {
      this.setData({showDxyzmBox: true})
     }
  },

  onModalConfirm2() {
    console.log('用户点击确认');
    this.closeModal();
    this.setData({
      checked: true
    });
    this.setData({showDxyzmBox: true})
  },
  onModalConfirm2() {
    console.log('用户点击确认');
    this.closeModal2();
    this.setData({
      checked: true
    });
    this.setData({showDxyzmBox: true})
  },
  onModalCancel2() {
    this.closeModal2();
  },
  toggleCheck () {
    this.setData({
      checked: !this.data.checked
    });
    // 可选：触发勾选事件（如提交表单时获取状态）
    console.log('当前勾选状态：', this.data.checked);
  },
  goback () {
    this.setData({showDxyzmBox: false})
  },
  onVerifyCode2Input () {
    this.setData({
      showErrorMag: false
    })
  },
  // 登录成功后
  handelsuccess () {
    wx.reLaunch({
      url: '/pages/infoYz/index'
    })
  },
  clearIntervalfn () {
    clearInterval(this.countdownTimer);
  },
  opentimes () {
      this.clearIntervalfn()
      this.setData({ countdown: 4 });
      this.countdownTimer = setInterval(() => {
        const { countdown } = this.data;
        if (countdown <= 0) {
          clearInterval(this.countdownTimer);
          // 倒计时结束后可添加重新发送逻辑
          return;
        }
        this.setData({ countdown: countdown - 1 });
      }, 1000);
  },
  nexts () {
      // 手机号有效时执行下一步逻辑
      if (this.data.isPhoneValid) {
        console.log('verifyCode', this.data.verifyCode)
        console.log('verifyCode2', this.data.verifyCode2)
        if (this.data.verifyCode.toLowerCase() === this.data.verifyCode2.toLowerCase()) {
          console.log('手机号有效，执行下一步');
          if (!this.countdownTimer) {
            this.opentimes()
          }
          this.setData({ isModalShow2: true });
        } else {
          console.log('验证码错误');
          this.refreshVerifyCode()
          this.setData({
            showErrorMag: true
          })
        }
      }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.generateVerifyCode();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.clearIntervalfn()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
   // 生成随机验证码
   generateVerifyCode() {
    let code = '';
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    
    for (let i = 0; i < this.data.verifyCodeLength; i++) {
      const randomIndex = Math.floor(Math.random() * chars.length);
      code += chars.charAt(randomIndex);
    }
    
    this.setData({ verifyCode: code });
    this.drawVerifyCode();
  },
  
  // 绘制验证码到Canvas
  drawVerifyCode() {
    const ctx = wx.createCanvasContext('verifyCanvas', this);
    const width = 120;
    const height = 40;
    
    // 绘制背景
    ctx.setFillStyle('#f5f5f5');
    ctx.fillRect(0, 0, width, height);
    
    // 绘制随机字符
    const code = this.data.verifyCode;
    const charWidth = width / (code.length + 1);
    
    for (let i = 0; i < code.length; i++) {
      const x = (i + 1) * charWidth;
      const y = height / 2 + Math.random() * 10 - 5;
      const fontSize = 20 + Math.random() * 8;
      const angle = Math.random() * 30 * Math.PI / 180;
      
      ctx.setFontSize(fontSize);
      ctx.setTextBaseline('middle');
      ctx.setTextAlign('center');
      ctx.setFillStyle(`rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`);
      
      ctx.save();
      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.fillText(code[i], 0, 0);
      ctx.restore();
    }
    
    // 添加干扰线
    for (let i = 0; i < 3; i++) {
      ctx.beginPath();
      ctx.moveTo(Math.random() * width, Math.random() * height);
      ctx.lineTo(Math.random() * width, Math.random() * height);
      ctx.setStrokeStyle(`rgb(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200})`);
      ctx.setLineWidth(1);
      ctx.stroke();
    }
    
    // 添加噪点
    for (let i = 0; i < 50; i++) {
      ctx.beginPath();
      ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI);
      ctx.setFillStyle(`rgb(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200})`);
      ctx.fill();
    }
    
    ctx.draw();
  },
  
  // 刷新验证码
  refreshVerifyCode() {
    this.generateVerifyCode();
  }
})